/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.WebIDE.ejb.sessions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.WebIDE.ejb.entities.*;
import org.WebIDE.ejb.sessions.exceptions.*;

/**
 *
 * @author huy
 */
@Stateless
public class TopicsFacade implements TopicsFacadeLocal, TopicsFacadeRemote {
    @Resource
    private UserTransaction utx = null;
    @PersistenceContext(unitName = "WebIDE-ejbPU")
    private EntityManager _em;
/*
    public void create(Topics topics) {
        em.persist(topics);
    }

    public void edit(Topics topics) {
        em.merge(topics);
    }
*/
    public void remove(Topics topics) {
        _em.remove(_em.merge(topics));
    }

    public Topics find(Object id) {
        return _em.find(Topics.class, id);
    }

    public List<Topics> findAll() {
        return _em.createQuery("select object(o) from Topics as o").getResultList();
    }


    public EntityManager getEntityManager() {
        return _em;
    }

    public void create(Topics topics) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (topics.getRepliesCollection() == null) {
            topics.setRepliesCollection(new ArrayList<Replies>());
        }
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Users userName = topics.getUserName();
            if (userName != null) {
                userName = em.getReference(userName.getClass(), userName.getUserName());
                topics.setUserName(userName);
            }
            Collection<Replies> attachedRepliesCollection = new ArrayList<Replies>();
            for (Replies repliesCollectionRepliesToAttach : topics.getRepliesCollection()) {
                repliesCollectionRepliesToAttach = em.getReference(repliesCollectionRepliesToAttach.getClass(), repliesCollectionRepliesToAttach.getId());
                attachedRepliesCollection.add(repliesCollectionRepliesToAttach);
            }
            topics.setRepliesCollection(attachedRepliesCollection);
            em.persist(topics);
            if (userName != null) {
                userName.getTopicsCollection().add(topics);
                userName = em.merge(userName);
            }
            for (Replies repliesCollectionReplies : topics.getRepliesCollection()) {
                Topics oldTopicIdOfRepliesCollectionReplies = repliesCollectionReplies.getTopicId();
                repliesCollectionReplies.setTopicId(topics);
                repliesCollectionReplies = em.merge(repliesCollectionReplies);
                if (oldTopicIdOfRepliesCollectionReplies != null) {
                    oldTopicIdOfRepliesCollectionReplies.getRepliesCollection().remove(repliesCollectionReplies);
                    oldTopicIdOfRepliesCollectionReplies = em.merge(oldTopicIdOfRepliesCollectionReplies);
                }
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findTopics(topics.getId()) != null) {
                throw new PreexistingEntityException("Topics " + topics + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void edit(Topics topics) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Topics persistentTopics = em.find(Topics.class, topics.getId());
            Users userNameOld = persistentTopics.getUserName();
            Users userNameNew = topics.getUserName();
            Collection<Replies> repliesCollectionOld = persistentTopics.getRepliesCollection();
            Collection<Replies> repliesCollectionNew = topics.getRepliesCollection();
            if (userNameNew != null) {
                userNameNew = em.getReference(userNameNew.getClass(), userNameNew.getUserName());
                topics.setUserName(userNameNew);
            }
            Collection<Replies> attachedRepliesCollectionNew = new ArrayList<Replies>();
            for (Replies repliesCollectionNewRepliesToAttach : repliesCollectionNew) {
                repliesCollectionNewRepliesToAttach = em.getReference(repliesCollectionNewRepliesToAttach.getClass(), repliesCollectionNewRepliesToAttach.getId());
                attachedRepliesCollectionNew.add(repliesCollectionNewRepliesToAttach);
            }
            repliesCollectionNew = attachedRepliesCollectionNew;
            topics.setRepliesCollection(repliesCollectionNew);
            topics = em.merge(topics);
            if (userNameOld != null && !userNameOld.equals(userNameNew)) {
                userNameOld.getTopicsCollection().remove(topics);
                userNameOld = em.merge(userNameOld);
            }
            if (userNameNew != null && !userNameNew.equals(userNameOld)) {
                userNameNew.getTopicsCollection().add(topics);
                userNameNew = em.merge(userNameNew);
            }
            for (Replies repliesCollectionOldReplies : repliesCollectionOld) {
                if (!repliesCollectionNew.contains(repliesCollectionOldReplies)) {
                    repliesCollectionOldReplies.setTopicId(null);
                    repliesCollectionOldReplies = em.merge(repliesCollectionOldReplies);
                }
            }
            for (Replies repliesCollectionNewReplies : repliesCollectionNew) {
                if (!repliesCollectionOld.contains(repliesCollectionNewReplies)) {
                    Topics oldTopicIdOfRepliesCollectionNewReplies = repliesCollectionNewReplies.getTopicId();
                    repliesCollectionNewReplies.setTopicId(topics);
                    repliesCollectionNewReplies = em.merge(repliesCollectionNewReplies);
                    if (oldTopicIdOfRepliesCollectionNewReplies != null && !oldTopicIdOfRepliesCollectionNewReplies.equals(topics)) {
                        oldTopicIdOfRepliesCollectionNewReplies.getRepliesCollection().remove(repliesCollectionNewReplies);
                        oldTopicIdOfRepliesCollectionNewReplies = em.merge(oldTopicIdOfRepliesCollectionNewReplies);
                    }
                }
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = topics.getId();
                if (findTopics(id) == null) {
                    throw new NonexistentEntityException("The topics with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Topics topics;
            try {
                topics = em.getReference(Topics.class, id);
                topics.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The topics with id " + id + " no longer exists.", enfe);
            }
            Users userName = topics.getUserName();
            if (userName != null) {
                userName.getTopicsCollection().remove(topics);
                userName = em.merge(userName);
            }
            Collection<Replies> repliesCollection = topics.getRepliesCollection();
            for (Replies repliesCollectionReplies : repliesCollection) {
                repliesCollectionReplies.setTopicId(null);
                repliesCollectionReplies = em.merge(repliesCollectionReplies);
            }
            em.remove(topics);
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public List<Topics> findTopicsEntities() {
        return findTopicsEntities(true, -1, -1);
    }

    public List<Topics> findTopicsEntities(int maxResults, int firstResult) {
        return findTopicsEntities(false, maxResults, firstResult);
    }

    private List<Topics> findTopicsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Topics as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            //em.close();
        }
    }

    public Topics findTopics(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Topics.class, id);
        } finally {
            //em.close();
        }
    }

    public int getTopicsCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Topics as o").getSingleResult()).intValue();
        } finally {
            //em.close();
        }
    }

    // my code
    public int getMaxID() {
        EntityManager em = getEntityManager();
        try {
            Integer kq = ((Integer)em.createQuery("select MAX(t.id) from Topics t").getSingleResult());
            if (kq == null)
                return 0;
            return kq.intValue();
        } finally {
            
        }
    }
    
    public List<Replies> getReplies(int topicID) {
        EntityManager em = getEntityManager();
        try {
            Topics top = em.find(Topics.class, topicID);
            top.getRepliesCollection().size();
            return (List<Replies>) top.getRepliesCollection();
        } finally {
            
        }
    } 
}
